/*
 * Copyright 2009 XueSong Guo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.webwheel.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 向浏览器发送javascript代码的结果
 */
public class JavascriptResult extends SimpleResult {

    protected String scripts;

    /**
     * 构造方法
     * @param scripts javascript代码，例如“alert('hi')”
     */
    public JavascriptResult(String scripts) {
        this.scripts = scripts;
    }

    /**
     * 通过向客户端发送简单的html页面，包含一段javascript代码，来实现输出javascript代码到浏览器的结果。
     * @throws IOException 输入输出异常
     */
    public void render() throws IOException {
        HttpServletResponse response = context.getResponse();
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter pw = response.getWriter();
        pw.write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta http-equiv=\"Cache-Control\" content=\"no-cache\"/><head><script type=\"text/javascript\">");
        if(scripts!=null) pw.write(scripts);
        pw.write("</script></head><body></body></html>");
    }
}
